//
//  DeviceControlVC.m
//  FishTank
//
//  Created by Scott Zhu on 14/11/28.
//  Copyright (c) 2014年 Scott Zhu. All rights reserved.
//

#import "DeviceControlVC.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ControlPeriods.h"
#import "DeviceSun.h"
#import "DeviceStateView.h"
#import "CallPoliceSettingVC.h"
#import "NoConnectionBgVideo.h" //视频无连接背景图
#import "DevicePowerView.h"
#import "PowerView.h"
#import "BoyeTool.h"
#import "DeviceListVC.h"
@interface DeviceControlVC ()<UIAlertViewDelegate>
@property (nonatomic) BOOL isDisappear;


@property (nonatomic) BOOL isLightOn;
@property (nonatomic) BOOL isWaterOn;
@property (nonatomic) BOOL isDisinfectOn;
@property (nonatomic) BOOL isAutoControlOn;

@property (nonatomic) BOOL isVideoOn;

@property (nonatomic, strong) DeviceStateView * stateView;
@property (nonatomic, strong) UIImageView *fullVideoImage;
@property (nonatomic, strong) NoConnectionBgVideo *videoBgView;
@property (nonatomic, strong) UIButton *fullButton;
@property (nonatomic, strong) DevicePowerView *devicePowerView1;
@property (nonatomic, strong) DevicePowerView *devicePowerView2;
//是否第一次检测到网络
@property (nonatomic) BOOL isFirst;
//add by hebidu @2016年09月21日
@property (nonatomic) INT32 lastSessionID;
@end

@implementation DeviceControlVC
@synthesize deviceInfo = _deviceInfo;
@synthesize temperatureLabel = _temperatureLabel;
@synthesize phLabel = _phLabel;
@synthesize videoImage = _videoImage;
@synthesize lightButton = _lightButton;
@synthesize waterButton = _waterButton;
@synthesize videoButton = _videoButton;
@synthesize photoButton = _photoButton;
@synthesize disinfectButton = _disinfectButton;
@synthesize autoControlButton = _autoControlButton;

@synthesize isWaterOn = _isWaterOn;
@synthesize isLightOn = _isLightOn;
@synthesize isDisinfectOn = _isDisinfectOn;
@synthesize isAutoControlOn = _isAutoControlOn;
@synthesize isVideoOn = _isVideoOn;


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:_deviceInfo.name];
    _isWaterOn = NO;
    _isLightOn = NO;
    _isDisinfectOn = NO;
    _isAutoControlOn = NO;
    _isVideoOn = NO;
    _lastSessionID = -1;
    _isDisappear = NO;
    
    [self createRightBarButtonItemWithTitle:@"设定"];
    
    self.stateView = [[DeviceStateView alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH -  100, 330)];
    [self.view addSubview:self.stateView];
    self.stateView.hidden = YES;
    self.videoImage.userInteractionEnabled = NO;
     
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(videoButtonPressed:)];
//    [_videoImage addGestureRecognizer:tapGesture];
    
    UILongPressGestureRecognizer *lightLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                                                 action:@selector(lightButtonLongPressed:)];
    [_lightButton addGestureRecognizer:lightLongPress];
    
    UILongPressGestureRecognizer *waterLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                                                 action:@selector(waterButtonLongPressed:)];
    [_waterButton addGestureRecognizer:waterLongPress];
    
    UILongPressGestureRecognizer *disinfectLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
                                                                                                     action:@selector(disinfectButtonLongPressed:)];
    [_disinfectButton addGestureRecognizer:disinfectLongPress];
    
    
    [self _initFullScreenButton];

}

#pragma marks - 全屏按钮 状态视图
- (void)_initFullScreenButton{
    
    NoConnectionBgVideo *videoBgView = [[NoConnectionBgVideo alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, 　SCREEN_WIDTH)];
    self.videoBgView = videoBgView;
    _videoImage.image = [self createImageFromView:videoBgView];
    
    
    _videoImage.userInteractionEnabled = YES;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_videoImage addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_videoImage.mas_bottom).offset(-10);
        make.right.equalTo(_videoImage.mas_right).offset(-10);
        make.size.mas_equalTo(CGSizeMake(25, 25));
    }];
    [btn setBackgroundImage:[UIImage imageNamed:@"我家的鱼缸"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(fullScreenButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    DeviceSun *device = [DeviceSun defaultDevice];
    //只有AQ211板支持功率
    if(device.version == AQ211){

    DevicePowerView *devicePowerView = [[DevicePowerView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 45)];
    [_videoImage addSubview:devicePowerView];
        
        devicePowerView.floodlightView.title = @"灯光照明";
        devicePowerView.floodlightView.value = device.floodlightPower;
        devicePowerView.floodlightView.type = YES;
        
        devicePowerView.waterPumpView.title = @"冲浪水泵";
        devicePowerView.waterPumpView.value = device.waterPumpPower;
        devicePowerView.waterPumpView.type = NO;
        
        devicePowerView.lampView.title = @"紫外线灯";
        devicePowerView.lampView.value = device.lampPower;
        devicePowerView.lampView.type = NO;
        
        devicePowerView.cyclePumpView.title = @"循环水泵";
        devicePowerView.cyclePumpView.value = device.cyclePumpPower;
        devicePowerView.cyclePumpView.type = YES;
        self.devicePowerView1 = devicePowerView;
    }
}

- (void)fullScreenButtonAction:(UIButton *)button{
    //隐藏导航栏 和 状态栏
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    _videoImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    
    UIImageView *fullVideoImage = [[UIImageView alloc] init];
    fullVideoImage.transform = CGAffineTransformMakeRotation(M_PI /2);
    fullVideoImage.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    fullVideoImage.image = _videoImage.image;
    fullVideoImage.userInteractionEnabled = YES;
    fullVideoImage.contentMode = UIViewContentModeScaleToFill;
    [self.view addSubview:fullVideoImage];
   
    
    DeviceSun *device = [DeviceSun defaultDevice];
    //只有AQ211板支持功率
    if(device.version == AQ211){
        
        DevicePowerView *devicePowerView = [[DevicePowerView alloc] initWithFrame:CGRectMake((SCREEN_HEIGHT - SCREEN_WIDTH) / 2, 10, SCREEN_WIDTH, 45)];
        [fullVideoImage addSubview:devicePowerView];
        
        devicePowerView.floodlightView.title = @"灯光照明";
        devicePowerView.floodlightView.value = device.floodlightPower;
        devicePowerView.floodlightView.type = YES;
        
        devicePowerView.waterPumpView.title = @"冲浪水泵";
        devicePowerView.waterPumpView.value = device.waterPumpPower;
        devicePowerView.waterPumpView.type = NO;
        
        devicePowerView.lampView.title = @"紫外线灯";
        devicePowerView.lampView.value = device.lampPower;
        devicePowerView.lampView.type = NO;
        
        devicePowerView.cyclePumpView.title = @"循环水泵";
        devicePowerView.cyclePumpView.value = device.cyclePumpPower;
        devicePowerView.cyclePumpView.type = YES;
        self.devicePowerView2 = devicePowerView;
    }

    UIButton *fullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    fullButton.frame = CGRectMake(SCREEN_HEIGHT - 60, SCREEN_WIDTH - 50, 35, 35);
    [fullVideoImage addSubview:fullButton];
    [fullButton setBackgroundImage:[UIImage imageNamed:@"我家的鱼缸_2"] forState:UIControlStateNormal];
    [fullButton addTarget:self action:@selector(removeViewAction:) forControlEvents:UIControlEventTouchUpInside];
    self.fullVideoImage = fullVideoImage;
    self.fullVideoImage.contentMode = UIViewContentModeScaleToFill;
}

- (void)removeViewAction:(UIButton *)button{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self.fullVideoImage removeFromSuperview];
}




-(UIImage*)createImageFromView:(UIView*)view{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(view.bounds.size);
    CGContextRef currnetContext = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:currnetContext];
    // 从当前context中创建一个改变大小后的图片
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    return image;
}



// 创建导航栏右侧的按钮，样式是文字的
- (void)createRightBarButtonItemWithTitle:(NSString *)title {
    
    
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 20)];
    [rightButton setTitle:title forState:UIControlStateNormal];
    [rightButton setTitleColor:rgba(0, 140, 210, 1) forState:UIControlStateNormal];
    rightButton.titleLabel.font = FONT(14);
    rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
  //debug模式下 显示测试按钮
#if defined(DEBUG)||defined(_DEBUG)
    NSMutableArray *items = [NSMutableArray arrayWithCapacity:1];
    [items addObject:rightBarButton];
    UIButton * testButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 36, 20)];//查看状态
    [testButton setTitle:@"测试" forState:UIControlStateNormal];
    testButton.titleLabel.font = FONT(14);
    [testButton setTitleColor:rgba(0, 140, 210, 1) forState:UIControlStateNormal];
    [testButton addTarget:self action:@selector(testAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton2 = [[UIBarButtonItem alloc] initWithCustomView:testButton];
    [items addObject:rightBarButton2];
    self.navigationItem.rightBarButtonItems = items;

    
#endif
    
    
    
   }

// 导航栏右侧按钮事件
- (void)rightAction:(UIButton *)button {
    CallPoliceSettingVC *vc = [[CallPoliceSettingVC alloc] init];
    vc.deviceInfo = _deviceInfo;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)testAction:(UIButton *)button{
    
    button.selected = !button.selected;
    if (button.selected) {
        self.stateView.hidden = NO;
//        [UIView animateWithDuration:0.15 animations:^{
//            self.stateView.height = 330;
//        }];
    }else{
//        [UIView animateWithDuration:0.15 animations:^{
//            self.stateView.height = 0;
//        }];
        self.stateView.hidden = YES;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    _isDisappear = NO;
    [self listenNetworkStatus];
    
}

-(void) listenNetworkStatus{
    
    _isFirst = NO;
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"网络环境改变了");
        if(_isFirst){

            //                [SVProgressHUD showErrorWithStatus:@"您的网络发生变化，请重新连接!" withDuration:3];
            [self showAlertThenExit];
            
//            dispatch_async(dispatch_get_main_queue(),^{
//                [self.navigationController popViewControllerAnimated:YES];
//            });
            
            
        }
        
        _isFirst = YES;
      
    }];
    
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

-(void)viewDidLayoutSubviews
{
    [self initUI];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self reconnect:2];
    
    DeviceSun * device = [DeviceSun defaultDevice];
    
    self.stateView.versionText = device.versionInfo;

}

-(void) getDeviceState{
    [SVProgressHUD showWithStatus:@"正在获取数据..." maskType:SVProgressHUDMaskTypeBlack];
    [[APIs sharedInstance] listenOnSensorsWithTimeout:8000
                                             password:_deviceInfo.password
                                              updated:^(float temperature, float ph, Byte controlByte, NSString *lockStatus)
     {
         [SVProgressHUD dismiss];
         
         DeviceSun * device = [DeviceSun defaultDevice];
         
         //只有AQ211板支持功率
         if(device.version == AQ211){
             self.devicePowerView1.floodlightView.value = device.floodlightPower;
             self.devicePowerView2.floodlightView.value = device.floodlightPower;
             
             self.devicePowerView1.waterPumpView.value = device.waterPumpPower;
             self.devicePowerView2.waterPumpView.value = device.waterPumpPower;
             
             self.devicePowerView1.lampView.value = device.lampPower;
             self.devicePowerView2.lampView.value = device.lampPower;
             
             self.devicePowerView1.cyclePumpView.value = device.cyclePumpPower;
             self.devicePowerView2.cyclePumpView.value = device.cyclePumpPower;
         }
         
         
         self.stateView.stateText = device.state;
         if (temperature > 100 || temperature < 0) {
             temperature = 0.00;
         }
         _temperatureLabel.adjustsFontSizeToFitWidth = YES;
         [_temperatureLabel setText:[NSString stringWithFormat:@"%.1f℃", temperature]];
         [_phLabel setText:[NSString stringWithFormat:@"%.1f", ph]];
         _isLightOn = (controlByte & 0x01) > 0? YES:NO;
         [_lightButton setImage:[UIImage imageNamed:(_isLightOn?@"LightOn":@"LightOff")] forState:UIControlStateNormal];
         [_lightButton setEnabled:YES];
         
         _isWaterOn = (controlByte & 0x02) > 0? YES:NO;
         [_waterButton setImage:[UIImage imageNamed:(_isWaterOn?@"WaterOn":@"WaterOff")] forState:UIControlStateNormal];
         [_waterButton setEnabled:YES];
         
         _isDisinfectOn = (controlByte & 0x10) > 0? YES:NO;
         [_disinfectButton setImage:[UIImage imageNamed:(_isDisinfectOn?@"DisinfectOn":@"DisinfectOff")] forState:UIControlStateNormal];
         [_disinfectButton setEnabled:YES];
         
         _isAutoControlOn = (controlByte & 0x80) > 0? YES:NO;
         [_autoControlButton setImage:[UIImage imageNamed:(_isAutoControlOn?@"ModeOn":@"ModeOff")] forState:UIControlStateNormal];
         [_autoControlButton setEnabled:YES];
         if (![self.autoStateLabel.text isEqualToString:@"请切换到手动模式后再操作！"])
         {
             [self.autoStateLabel setText:(_isAutoControlOn? @"当前模式：自动": @"当前模式：手动")];
         }
         
         
     } interupted:^(NSInteger errorCode) {
         [SVProgressHUD dismiss];
         NSLog(@"listener interaputed = %ld",errorCode);
         if(errorCode == ERROR_NEED_RECONNECT){
             [self showAlertThenExit];
             //             [self reconnect];
         }
     }];
    
}

-(void) showAlertThenExit{
    
    
    [SVProgressHUD dismiss];
    
    if(!(self.isViewLoaded && self.view.window)){
        return ;
    }
    
#if __IPHONE_OS_VERSION_MAaX_ALLOWED >= _IPHONE80_
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")){
    NSString *title = NSLocalizedString(@"连接出错", nil);
    NSString *message = NSLocalizedString(@"请重新连接设备.", nil);
    NSString *otherButtonTitle = @"确定";
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [alertController addAction:otherAction];
        
    [self presentViewController:alertController animated:YES completion:nil];
    }
#else
    
    [[[UIAlertView alloc] initWithTitle:@"❌连接出错"
                                message:@"请重新连接设备"
                               delegate:self
                      cancelButtonTitle:@"确定"
                      otherButtonTitles:nil, nil] show];
    
#endif
    
}

#pragma marks -- UIAlertViewDelegate --
//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"clickButtonAtIndex:%ld",(long)buttonIndex);
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
    _isDisappear = YES;
    
//    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
    NSLog(@"设备控制消失了");
    if(_isVideoOn){
//        [[APIs sharedInstance] setIsListenOnVideo:NO];
//        [[APIs sharedInstance] sendStopVideoRequest:_deviceInfo.password];
        [self videoButtonPressed:nil];
        NSLog(@"视频消失关闭连接");
    }
    
    [[APIs sharedInstance] setIsListenOnSensors:NO];
    
    
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:SHOW_PERIODS_SETTING])
    {
        PeriodsSettingVC *periodsSettingVC = (PeriodsSettingVC *)[segue destinationViewController];
        [periodsSettingVC setControlPeriods:(ControlPeriods *)sender];
        [periodsSettingVC setDeviceInfo:_deviceInfo];
    }
}


#pragma -mark- Custom methods

- (void)initUI
{
    NSInteger borderWidth = 1;
    self.temperatureBlock.layer.borderWidth = borderWidth;
    self.temperatureBlock.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientTemperatureBlock = [CAGradientLayer layer];
    gradientTemperatureBlock.frame = self.temperatureBlock.layer.frame;
    gradientTemperatureBlock.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
//    NSLog(@"Temp size = %@; Gradient size = %@", NSStringFromCGSize(self.temperatureBlock.frame.size), NSStringFromCGSize(gradientTemperatureBlock.frame.size));
//    gradientTemperatureBlock.frame = CGRectMake(10, 0, CGRectGetWidth(self.temperatureBlock.frame), CGRectGetHeight(self.temperatureBlock.frame));
    [self.temperatureBlock.layer insertSublayer:gradientTemperatureBlock atIndex:0];
    
    self.phBlock.layer.borderWidth = borderWidth;
    self.phBlock.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientPHBlock = [CAGradientLayer layer];
    gradientPHBlock.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientPHBlock.frame = self.phBlock.bounds;
    [self.phBlock.layer insertSublayer:gradientPHBlock atIndex:0];
    
    self.lightView.layer.borderWidth = borderWidth;
    self.lightView.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientLightView = [CAGradientLayer layer];
    gradientLightView.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientLightView.frame = self.lightView.bounds;
    [self.lightView.layer insertSublayer:gradientLightView atIndex:0];
    
    self.waterView.layer.borderWidth = borderWidth;
    self.waterView.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientWaterView = [CAGradientLayer layer];
    gradientWaterView.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientWaterView.frame = self.waterView.bounds;
    [self.waterView.layer insertSublayer:gradientWaterView atIndex:0];
    
    self.disinfectView.layer.borderWidth = borderWidth;
    self.disinfectView.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientDisinfectView = [CAGradientLayer layer];
    gradientDisinfectView.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientDisinfectView.frame = self.disinfectView.bounds;
    [self.disinfectView.layer insertSublayer:gradientDisinfectView atIndex:0];
    
    self.modeView.layer.borderWidth = borderWidth;
    self.modeView.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientModeView = [CAGradientLayer layer];
    gradientModeView.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientModeView.frame = self.modeView.bounds;
    [self.modeView.layer insertSublayer:gradientModeView atIndex:0];
    
    self.videoView.layer.borderWidth = borderWidth;
    self.videoView.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientVideoView = [CAGradientLayer layer];
    gradientVideoView.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientVideoView.frame = self.videoView.bounds;
    [self.videoView.layer insertSublayer:gradientVideoView atIndex:0];
    
    self.photoView.layer.borderWidth = borderWidth;
    self.photoView.layer.borderColor = [UIColor whiteColor].CGColor;
    CAGradientLayer *gradientPhotoView = [CAGradientLayer layer];
    gradientPhotoView.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientPhotoView.frame = self.photoView.bounds;
    [self.photoView.layer insertSublayer:gradientPhotoView atIndex:0];
    
    CAGradientLayer *gradientAutoBlock = [CAGradientLayer layer];
    gradientAutoBlock.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:0.89 green:0.89 blue:0.89 alpha:1.0] CGColor], (id)[[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] CGColor], nil];
    gradientAutoBlock.frame = self.autoBlock.bounds;
    [self.autoBlock.layer insertSublayer:gradientAutoBlock atIndex:0];
    
//    if (IS_IPHONE_4_OR_LESS)
//    {
//        [self.lightStick setHidden:YES];
//        [self.lightSettingLabel setHidden:YES];
//        
//        [self.waterStick setHidden:YES];
//        [self.waterSettingLabel setHidden:YES];
//        
//        [self.disinfectStick setHidden:YES];
//        [self.disinfectSettingLabel setHidden:YES];
//    }
//    if(IS_IPHONE_5)
//    {
//        [self.lightSettingLabel setFont:[UIFont systemFontOfSize:11]];
//        [self.waterSettingLabel setFont:[UIFont systemFontOfSize:11]];
//        [self.disinfectSettingLabel setFont:[UIFont systemFontOfSize:11]];
//    }
}

-(void)postMessage
{
    [self.autoStateLabel setText:@"请切换到手动模式后再操作！"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.autoStateLabel setText:(_isAutoControlOn? @"当前模式：自动": @"当前模式：手动")];
});
}

#pragma -mark- Actions
- (IBAction)lightButtonPressed:(id)sender
{
    if (_isAutoControlOn)
    {
        [self postMessage];
        return;
    }
    _isLightOn = !_isLightOn;
   [_lightButton setImage:[UIImage imageNamed:(_isLightOn?@"LightOn":@"LightOff")] forState:UIControlStateNormal];
   [[APIs sharedInstance] setLightStatus:_isLightOn
                              waterStatus:_isWaterOn
                          disinfectStatus:_isDisinfectOn
                        autoControlStatus:_isAutoControlOn
                             withPassword:_deviceInfo.password];
}

- (void)lightButtonLongPressed:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        [[APIs sharedInstance] controlPeriodWith:Light
                                        password:_deviceInfo.password
                                         success:^(ControlPeriods *controlPeriods)
         {
        
        [self performSegueWithIdentifier:SHOW_PERIODS_SETTING sender:controlPeriods];
             
         } failure:^(NSInteger errorCode) {
             [[[UIAlertView alloc] initWithTitle:@"❌连接失败，，请重连"
                                         message:[NSString stringWithFormat:@"错误代码：%ld", (long)errorCode ]
                                        delegate:nil
                               cancelButtonTitle:@"好的"
                               otherButtonTitles:nil, nil] show];
         }];
    }
}

- (IBAction)waterButtonPressed:(id)sender
{
    if (_isAutoControlOn)
    {
        [self postMessage];
        return;
    }
    _isWaterOn = !_isWaterOn;
    [_waterButton setImage:[UIImage imageNamed:(_isWaterOn?@"WaterOn":@"WaterOff")] forState:UIControlStateNormal];
    [[APIs sharedInstance] setLightStatus:_isLightOn
                              waterStatus:_isWaterOn
                          disinfectStatus:_isDisinfectOn
                        autoControlStatus:_isAutoControlOn
                             withPassword:_deviceInfo.password];
}

- (void)waterButtonLongPressed:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        [[APIs sharedInstance] controlPeriodWith:Water
                                        password:_deviceInfo.password
                                         success:^(ControlPeriods *controlPeriods)
         {
             [self performSegueWithIdentifier:SHOW_PERIODS_SETTING sender:controlPeriods];
             
         } failure:^(NSInteger errorCode) {
             [[[UIAlertView alloc] initWithTitle:@"❌连接失败，请重连"
                                         message:[NSString stringWithFormat:@"错误代码：%ld", (long)errorCode ]
                                        delegate:nil
                               cancelButtonTitle:@"好的"
                               otherButtonTitles:nil, nil] show];
         }];
    }
}

-(void) setVideoOff{
    //UIImage *image = [UIImage imageNamed:@"蓝色图片"];
    UIImage *image = [self createImageFromView:self.videoBgView];
    [_videoImage setImage:image];
    [self.fullVideoImage setImage:image];
    [_videoButton setImage:[UIImage imageNamed:@"VideoOff"] forState:UIControlStateNormal];
}

- (IBAction)videoButtonPressed:(id)sender
{
    _isVideoOn = !_isVideoOn;
    
    //UIImage *image = [UIImage imageNamed:@"蓝色图片"];
    UIImage *image = [self createImageFromView:self.videoBgView];
    [_videoImage setImage:image];
    [self.fullVideoImage setImage:image];
    [_videoButton setImage:[UIImage imageNamed:(_isVideoOn?@"VideoOn":@"VideoOff")] forState:UIControlStateNormal];
    
    if (_isVideoOn)
    {
        NSLog(@"视频开关状态 ＝ %u", _isVideoOn);
        
        UINT32 timeout = 6000;
        __weak DeviceControlVC * that = self;
        [[APIs sharedInstance] listenOnVideoWithTimeout:timeout
                                               password:_deviceInfo.password
                                                updated:^(NSData *data)
        {
            if (_isVideoOn) {
                UIImage *image2 = [UIImage imageWithData:data];
                [_videoImage setImage:image2];
                [self.fullVideoImage setImage:image2];
                
            }else{
                [that setVideoOff];
            }
          
        }
        interupted:^(NSInteger errorCode)
        {
            //UIImage *image = [UIImage imageNamed:@"蓝色图片"];
            UIImage *image = [self createImageFromView:self.videoBgView];
             [_videoImage setImage:image];
             [self.fullVideoImage setImage:image];
            if(errorCode == ERROR_PPPP_DEVICE_NOT_ONLINE){
                [SVProgressHUD showErrorWithStatus:@"设备已断开" withDuration:3];
                return ;
            }
            
            if(errorCode == ERROR_PPPP_TIME_OUT){
                //超时的情况下，很多时候是视频帧数已经读取完毕，导致读取不到设备视频,这时候要暂停视频。
                NSLog(@"视频读取超时");
                [self videoButtonPressed:nil];
                return;
            }
            
            NSLog(@"listener interaputed = %ld",errorCode);
            if(errorCode == ERROR_NEED_RECONNECT){
                [self showAlertThenExit];
            }
            
            NSLog(@"video listener interaputed ret=%ld msg= %@",errorCode,[DeviceCtrl getPPPPReadMsg:(int)errorCode]);
        }];
    }
    else
    {
        [[APIs sharedInstance] setIsListenOnVideo:NO];
        [[APIs sharedInstance] sendStopVideoRequest:_deviceInfo.password];
    }
}
- (IBAction)photoButtonPressed:(id)sender
{
    if (_isVideoOn)
    {
        UIImage *image = [_videoImage image];
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        
        [library writeImageToSavedPhotosAlbum:[image CGImage]
                                  orientation:(ALAssetOrientation)[image imageOrientation]
                              completionBlock:^(NSURL *assetURL, NSError *error)
        {
            if (error)
            {
                [[[UIAlertView alloc] initWithTitle:@"图片保存失败"
                                            message:@"请确认已对本应用开启图片权限"
                                           delegate:nil
                                  cancelButtonTitle:@"好的"
                                  otherButtonTitles:nil, nil] show];
            } else
            {
                [[[UIAlertView alloc] initWithTitle:@"图片已成功保存至相册"
                                            message:nil
                                           delegate:nil
                                  cancelButtonTitle:@"好的"
                                  otherButtonTitles:nil, nil] show];
            }
        }];

    }
    else
    {
        [[[UIAlertView alloc] initWithTitle:@"视频未开启"
                                   message:nil
                                  delegate:nil
                         cancelButtonTitle:@"好的"
                          otherButtonTitles:nil, nil] show];
    }
}

- (IBAction)disinfectButtonPressed:(id)sender
{
    if (_isAutoControlOn)
    {
        [self postMessage];
        return;
    }
    _isDisinfectOn = !_isDisinfectOn;
    [_disinfectButton setImage:[UIImage imageNamed:(_isDisinfectOn?@"DisinfectOn":@"DisinfectOff")] forState:UIControlStateNormal];
    [[APIs sharedInstance] setLightStatus:_isLightOn
                              waterStatus:_isWaterOn
                          disinfectStatus:_isDisinfectOn
                        autoControlStatus:_isAutoControlOn
                             withPassword:_deviceInfo.password];
}

- (void)disinfectButtonLongPressed:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        [[APIs sharedInstance] controlPeriodWith:Disinfect
                                        password:_deviceInfo.password
                                         success:^(ControlPeriods *controlPeriods)
         {
    
           
             [self performSegueWithIdentifier:SHOW_PERIODS_SETTING sender:controlPeriods];
             
         } failure:^(NSInteger errorCode) {
             [[[UIAlertView alloc] initWithTitle:@"❌连接失败，请重连"
                                         message:[NSString stringWithFormat:@"错误代码：%ld", (long)errorCode ]
                                        delegate:nil
                               cancelButtonTitle:@"好的"
                               otherButtonTitles:nil, nil] show];
         }];
    }
}

- (IBAction)autoControlButtonPressed:(id)sender
{
    _isAutoControlOn = !_isAutoControlOn;
    if (_isAutoControlOn)
    {
        [_lightButton setEnabled:YES];
        [_waterButton setEnabled:YES];
        [_disinfectButton setEnabled:YES];
        [self.autoStateLabel setText:@"当前模式：自动"];
        
    }
    else
    {
        [_lightButton setEnabled:YES];
        [_waterButton setEnabled:YES];
        [_disinfectButton setEnabled:YES];
        [self.autoStateLabel setText:@"当前模式：手动"];
    }
    [_autoControlButton setImage:[UIImage imageNamed:(_isAutoControlOn?@"ModeOn":@"ModeOff")] forState:UIControlStateNormal];
    //[_autoControlButton setEnabled:NO];
    [[APIs sharedInstance] setLightStatus:_isLightOn
                              waterStatus:_isWaterOn
                          disinfectStatus:_isDisinfectOn
                        autoControlStatus:_isAutoControlOn
                             withPassword:_deviceInfo.password];
}
//重连
-(void) reconnect:(int) times{
    
    //[[APIs sharedInstance] close];
    [[APIs sharedInstance] close:self.lastSessionID];
//    [NSThread sleepForTimeInterval:100];
    
//    MWSS-000002-KFUPR
//
//    obUnB1N4
    
    if( self.deviceInfo == nil || self.deviceInfo.did == nil ){
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"重连时，设备信息缺失");
            
            [self.navigationController popViewControllerAnimated:YES];
        });
        return ;
        
    }
    
    __block DeviceControlVC * that = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
    
    [[APIs sharedInstance] connectWithUid: self.deviceInfo.did
                          lanSearchEnable:YES
                                  success:^(NSInteger session){
                                      
                                      NSLog(@"ReConnect success with session %ld", (long)session);
                                      self.lastSessionID = (INT32) session;
                                      
                                      dispatch_queue_t mainQueue = dispatch_get_main_queue();
                                      dispatch_async(mainQueue, ^{
                                          
                                          NSLog(@"连接成功会话ID %ld", (long)session);
                                          [SVProgressHUD dismiss];
                                          if (self.deviceInfo.password.length > 0) {
                                              [self getDeviceState];
                                              
                                          }else{
                                              
                                              [[[UIAlertView alloc] initWithTitle:@"❌连接失败，请重连"
                                                                          message:@"设备DID或密码错误"
                                                                         delegate:nil
                                                                cancelButtonTitle:@"确定"
                                                                otherButtonTitles:nil, nil] show];
                                              
                                              
                                          }
                                          
                                      });
                                      
                                  }
                                  failure:^(NSInteger errorCode) {
                                      NSString * errMsg = [that getErrMsg:errorCode];
                                      if(times - 1 > 0 ){
                                          [that reconnect:times-1];
                                          NSLog(@"连接失败 %d",times - 1);
                                          return;
                                      }
                                      
                                      dispatch_queue_t mainQueue = dispatch_get_main_queue();
                                      dispatch_async(mainQueue, ^{
                                          
                                          NSLog(@"Connect failed with errorCode %ld", (long)errorCode);
                                          [SVProgressHUD dismiss];
                                          if(self.isDisappear){
                                              return ;
                                          }
                                          
                                          [[[UIAlertView alloc] initWithTitle:@"请重试"
                                                                      message:[NSString stringWithFormat:@"网络不稳定或设备不在线"]
                                                                     delegate:nil
                                                            cancelButtonTitle:@"我知道了"
                                                            otherButtonTitles:nil, nil] show];
                                          
                                      });
                    }];
    });//end for dispatch

}

-(NSString *) getErrMsg:(int) errCode{
    return [DeviceCtrl getPPPPConnectErrMsg:errCode];
}

+(void) updateSubscribeToken:(DeviceInfo *) info
                     success:(void (^)(NSNumber *loadSubID ,NSNumber *  levelSubID ,NSNumber * tempSubID))success
                  interupted:(void (^)(NSInteger errorCode))interupted {
    
    BOOL bLoad = info.is_load_on;
    BOOL bLevel = info.is_level_on;
    BOOL bTemperature = info.is_temperature_on;
    
    NSLog(@"loadSubsribeID = %d levelSubsribeID = %d tempSubsribeID =%d", info.loadSubsribeID, info.levelSubsribeID, info.tempSubsribeID);
    NSNumber * oldLoadSubID = [[NSNumber alloc]initWithInt:info.loadSubsribeID];
    NSNumber * oldLevelSubID = [[NSNumber alloc]initWithInt:info.levelSubsribeID];
    NSNumber * oldTempSubID = [[NSNumber alloc]initWithInt:info.tempSubsribeID];
    
    __block NSNumber * loadSubID = [[NSNumber alloc]initWithInt:0];
    __block NSNumber * levelSubID = [[NSNumber alloc]initWithInt:0];
    __block NSNumber * tempSubID = [[NSNumber alloc]initWithInt:0];
    
//    if(oldLoadSubID.integerValue == 0 && oldLevelSubID.integerValue == 0 && oldTempSubID.integerValue == 0){
//        success(oldLoadSubID,oldLevelSubID,oldTempSubID);
//        return;
//    }
    
    if(!bLoad && !bLevel && !bTemperature){
        success(oldLoadSubID,oldLevelSubID,oldTempSubID);
        return;
    }
    
    
    if(![[APIs sharedInstance] checkPPPP]){
        
        [[APIs sharedInstance] reconnect:^(NSInteger session){
            //会话失效
            [[APIs sharedInstance]  querySubscribeToken:6000 password:info.password  success:^(NSString * temperature,NSString * level,NSString *load){
                
                //        NSString * ipnDeviceToken = [[CacheFacade sharedCache] get:@"IPN_DEVICE_TOKEN"];
                NSString * ipnDeviceToken = [[CacheFacade sharedCache] get:@"IPN_CLIENT_ID"];
                //        ipnDeviceToken = ipnClientID;
                
                //        NSLog(@"Device_token=%@,client id= %@",ipnDeviceToken,ipnClientID);
                int ret;
                
                if(bLoad){
                    UINT32 ids[1];
                    ids[0] = 0;
                    
                    ret = iPN_Subscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, ipnDeviceToken.UTF8String, ids);
                    
                    loadSubID = [[NSNumber alloc ]initWithInt:ids[0]];
                    NSLog(@"负载故障ret = %d,ids = %u",ret,ids[0]);
                    
                }else if(!bLoad &&  oldLoadSubID.integerValue > 0){
                    ret = iPN_UnSubscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, oldLoadSubID.intValue);
                    NSLog(@"负载故障取消ret = %d",ret);
                }
                
                if(bLevel){
                    UINT32 ids[1];
                    ids[0] = 0;
                    
                    ret = iPN_Subscribe_XinGe(level.UTF8String, IPN_AESKEY.UTF8String, ipnDeviceToken.UTF8String, ids);
                    
                    levelSubID = [[NSNumber alloc ]initWithInt:ids[0]];
                    
                    NSLog(@"水位故障ret = %d,ids = %u",ret,ids[0]);
                }else  if(!bLevel && oldLevelSubID.integerValue > 0){
                    ret = iPN_UnSubscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, oldLevelSubID.intValue);
                    NSLog(@"水位故障取消ret = %d",ret);
                    
                }
                
                if(bTemperature){
                    UINT32 ids[1];
                    ids[0] = 0;
                    
                    ret = iPN_Subscribe_XinGe(temperature.UTF8String, IPN_AESKEY.UTF8String, ipnDeviceToken.UTF8String, ids);
                    NSLog(@"温度故障ret   = %d ids= %u",ret,ids[0]);
                    tempSubID = [[NSNumber alloc ]initWithInt:ids[0]];
                    
                }else if(!bTemperature && oldTempSubID.intValue > 0){
                    ret = iPN_UnSubscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, oldTempSubID.intValue);
                    NSLog(@"温度故障取消ret = %d",ret);
                }
                
                //        NSLog(@"订阅设备令牌成功2 load= %@,level =%@,temp =%@",load,level,temperature);
                NSLog(@"订阅设备令牌成功2 load= %@,level =%@,temp =%@",loadSubID,levelSubID,tempSubID);
                
                
                [self updateSubscribeID:info :loadSubID :levelSubID :tempSubID];
                success(loadSubID ,levelSubID , tempSubID);
                
            } interupted:^(NSInteger errCode){
                
                NSLog(@"订阅设备令牌失败errCode ＝%ld",(long)errCode);
                interupted(errCode);
                
            }];
        } failure:^(NSInteger errCode){
            [SVProgressHUD showErrorWithStatus:@"设备断开连接,请重试" withDuration:3];
        }];

        
        
        
        
    }else{
        
        
        
        [[APIs sharedInstance]  querySubscribeToken:8000 password:info.password  success:^(NSString * temperature,NSString * level,NSString *load){
            
            //        NSString * ipnDeviceToken = [[CacheFacade sharedCache] get:@"IPN_DEVICE_TOKEN"];
            NSString * ipnDeviceToken = [[CacheFacade sharedCache] get:@"IPN_CLIENT_ID"];
            //        ipnDeviceToken = ipnClientID;
            
            //        NSLog(@"Device_token=%@,client id= %@",ipnDeviceToken,ipnClientID);
            int ret;
            
            if(bLoad){
                UINT32 ids[1];
                ids[0] = 0;
                
                ret = iPN_Subscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, ipnDeviceToken.UTF8String, ids);
                
                loadSubID = [[NSNumber alloc ]initWithInt:ids[0]];
                NSLog(@"负载故障ret = %d,ids = %u",ret,ids[0]);
                
            }else if(!bLoad &&  oldLoadSubID.integerValue > 0){
                ret = iPN_UnSubscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, oldLoadSubID.intValue);
                NSLog(@"负载故障取消ret = %d",ret);
            }
            
            if(bLevel){
                UINT32 ids[1];
                ids[0] = 0;
                
                ret = iPN_Subscribe_XinGe(level.UTF8String, IPN_AESKEY.UTF8String, ipnDeviceToken.UTF8String, ids);
                
                levelSubID = [[NSNumber alloc ]initWithInt:ids[0]];
                
                NSLog(@"水位故障ret = %d,ids = %u",ret,ids[0]);
            }else  if(!bLevel && oldLevelSubID.integerValue > 0){
                ret = iPN_UnSubscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, oldLevelSubID.intValue);
                NSLog(@"水位故障取消ret = %d",ret);
                
            }
            
            if(bTemperature){
                UINT32 ids[1];
                ids[0] = 0;
                
                ret = iPN_Subscribe_XinGe(temperature.UTF8String, IPN_AESKEY.UTF8String, ipnDeviceToken.UTF8String, ids);
                NSLog(@"温度故障ret   = %d ids= %u",ret,ids[0]);
                tempSubID = [[NSNumber alloc ]initWithInt:ids[0]];
                
            }else if(!bTemperature && oldTempSubID.intValue > 0){
                ret = iPN_UnSubscribe_XinGe(load.UTF8String, IPN_AESKEY.UTF8String, oldTempSubID.intValue);
                NSLog(@"温度故障取消ret = %d",ret);
            }
            
            //        NSLog(@"订阅设备令牌成功2 load= %@,level =%@,temp =%@",load,level,temperature);
            NSLog(@"订阅设备令牌成功2 load= %@,level =%@,temp =%@",loadSubID,levelSubID,tempSubID);
            
            
            [self updateSubscribeID:info :loadSubID :levelSubID :tempSubID];
            success(loadSubID ,levelSubID , tempSubID);
            
        } interupted:^(NSInteger errCode){
            
            NSLog(@"订阅设备令牌失败errCode ＝%ld",(long)errCode);
            interupted(errCode);
            
        }];

    }

    
    
    
}

+(void) updateSubscribeID:(DeviceInfo *) info :(NSNumber *)loadSubID :(NSNumber * ) levelSubID :(NSNumber *) tempSubID{
    DeviceInfo *deviceInfo;
    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
    id object =  [userDefault objectForKey:SENSEN_DEVICE_AQ];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:1];
    if (object != nil&&  [object respondsToSelector:@selector(initWithCoder:)]&& [object isKindOfClass:NSData.class]) {
        NSData * customData = (NSData * )object;
        array = [NSKeyedUnarchiver unarchiveObjectWithData:customData];
    }
    if (array.count > info.indexPath.section) {
        deviceInfo = [array objectAtIndex:info.indexPath.section];
    }

    if(loadSubID){
        deviceInfo.loadSubsribeID = [loadSubID intValue];
     }
    if(levelSubID){
         deviceInfo.levelSubsribeID = [levelSubID intValue];
    }
    if(tempSubID){
        deviceInfo.tempSubsribeID = [tempSubID intValue];
    }
    
    [array replaceObjectAtIndex:info.indexPath.section withObject:deviceInfo];
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:array];
    [userDefaults  setObject:data forKey:SENSEN_DEVICE_AQ ];//存储设备列表
    [userDefaults synchronize];
}


@end
